/**
 * There are code generation
 */
package com.neusoft.lohas.modules.ivm.web.order;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.neusoft.lohas.common.config.Global;
import com.neusoft.lohas.common.persistence.Page;
import com.neusoft.lohas.common.utils.DateUtils;
import com.neusoft.lohas.common.utils.FloatFormat;
import com.neusoft.lohas.common.utils.IdGen;
import com.neusoft.lohas.common.utils.StringUtils;
import com.neusoft.lohas.common.utils.excel.ExcelManager;
import com.neusoft.lohas.common.web.BaseController;
import com.neusoft.lohas.modules.ivm.entity.merchant.DeliveryFee;
import com.neusoft.lohas.modules.ivm.entity.merchant.DeliveryIndent;
import com.neusoft.lohas.modules.ivm.entity.merchant.Merchant;
import com.neusoft.lohas.modules.ivm.entity.merchant.ReceiptTime;
import com.neusoft.lohas.modules.ivm.entity.order.DeliveryDetail;
import com.neusoft.lohas.modules.ivm.entity.order.DeliveryInfo;
import com.neusoft.lohas.modules.ivm.entity.order.Order;
import com.neusoft.lohas.modules.ivm.entity.order.OrderDetail;
import com.neusoft.lohas.modules.ivm.entity.order.OrderDetailItem;
import com.neusoft.lohas.modules.ivm.entity.order.Prompt;
import com.neusoft.lohas.modules.ivm.entity.product.Product;
import com.neusoft.lohas.modules.ivm.entity.product.ProductInventoryDetail;
import com.neusoft.lohas.modules.ivm.entity.product.ProductOutDetail;
import com.neusoft.lohas.modules.ivm.entity.workflow.WorkFlowDetail;
import com.neusoft.lohas.modules.ivm.enums.order.OrderTypeEnum;
import com.neusoft.lohas.modules.ivm.enums.order.PayStatusEnum;
import com.neusoft.lohas.modules.ivm.enums.order.PayTypeEnum;
import com.neusoft.lohas.modules.ivm.service.merchant.DeliveryFeeService;
import com.neusoft.lohas.modules.ivm.service.merchant.DeliveryIndentService;
import com.neusoft.lohas.modules.ivm.service.merchant.ReceiptTimeService;
import com.neusoft.lohas.modules.ivm.service.order.DeliveryDetailService;
import com.neusoft.lohas.modules.ivm.service.order.DeliveryInfoService;
import com.neusoft.lohas.modules.ivm.service.order.OrderService;
import com.neusoft.lohas.modules.ivm.service.order.PromptService;
import com.neusoft.lohas.modules.ivm.service.order.orderDetailItemService;
import com.neusoft.lohas.modules.ivm.service.product.ProductOutDetailService;
import com.neusoft.lohas.modules.ivm.service.product.ProductService;
import com.neusoft.lohas.modules.ivm.service.workflow.WorkFlowDetailService;
import com.neusoft.lohas.modules.ivm.utils.ExportDeliveryUtil;
import com.neusoft.lohas.modules.ivm.utils.FileZip;
import com.neusoft.lohas.modules.sys.entity.User;
import com.neusoft.lohas.modules.sys.utils.UserUtils;

/**
 * 商品订单Controller
 * @author Jackie.Liu
 * @version 2014-12-16
 */
@Controller
@RequestMapping(value = "${adminPath}/ivm/order")
public class OrderController extends BaseController {

	@Autowired
	private OrderService orderService;
	@Autowired
	private ReceiptTimeService receiptTimeService;
	@Autowired
	private WorkFlowDetailService workFlowDetailService;
	@Autowired
	private ProductService productService;
	@Autowired
	private ProductOutDetailService productOutDetailService;
	@Autowired
	private DeliveryInfoService deliveryInfoService;
	@Autowired
	private DeliveryIndentService indentService;
	@Autowired
	private ExcelManager excelManager;
	@Autowired
	private DeliveryFeeService deliveryFeeService;
	@Autowired
	private PromptService promptService;
	@Autowired
	private DeliveryDetailService deliveryDetailService;
	@Autowired
	private orderDetailItemService orderDetailItemService;
	@ModelAttribute
	public Order get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return orderService.get(id);
		}else{
			return new Order();
		}
	}
	
	@RequiresPermissions("ivm:order:view")
	@RequestMapping(value = {"list", ""})
	public String list(Order order,
			@RequestParam(value="createStartDate", required=false, defaultValue="") String createStartDate, 
			@RequestParam(value="createEndDate", required=false, defaultValue="") String createEndDate, 
			@RequestParam(value="searchParam", required=false, defaultValue="") String searchParam,
			@RequestParam(value="type", required=false, defaultValue="") String type,  //此参数主要用于标记‘订单完成操作’
			@RequestParam(value="timeSlot", required=false, defaultValue="") String[] timeSlot,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		if (StringUtils.isBlank(order.getOrderType())) {
			order.setOrderType("1");
		}
		if(StringUtils.isNotBlank(searchParam)){
			try {
				searchParam = java.net.URLDecoder.decode(searchParam,"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		order.setMerchant(super.merchant);
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			order.setCreateBy(user);
		}
        Page<Order> page = orderService.find(new Page<Order>(request, response), order, createStartDate, createEndDate, searchParam, timeSlot, 0); 
        model.addAttribute("page", page);
        //获取商户收货时间段数据
		ReceiptTime receiptTime = receiptTimeService.findByMerchantId(order.getMerchant().getId());
		model.addAttribute("receiptTime", receiptTime);
		model.addAttribute("createStartDate", createStartDate);
		model.addAttribute("createEndDate", createEndDate);
        model.addAttribute("searchParam", searchParam);
        model.addAttribute("payTypes", PayTypeEnum.values());
        model.addAttribute("orderTypes", OrderTypeEnum.values());
        model.addAttribute("payStatus", PayStatusEnum.values());
        if(timeSlot.length==0){
        	model.addAttribute("timeSlot", "");
        }else{
        	String times="";
        	for(String ts:timeSlot){
        		times += ","+ts;
        	}
        	model.addAttribute("timeSlot", times.substring(1));
        }
        model.addAttribute("type", type);
		return "modules/ivm/order/orderList";
	}
	
	/**
	 * web端，鼠标向下滑动加载更多
	 * @param product
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "list/more")
	public @ResponseBody Object listMode(Order order,
			@RequestParam(value="createStartDate", required=false, defaultValue="") String createStartDate, 
			@RequestParam(value="createEndDate", required=false, defaultValue="") String createEndDate, 
			@RequestParam(value="searchParam", required=false, defaultValue="") String searchParam,
			@RequestParam(value="type", required=false, defaultValue="") String type,  //此参数主要用于标记‘订单完成操作’
			@RequestParam(value="timeSlot", required=false, defaultValue="") String[] timeSlot,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		if (StringUtils.isBlank(order.getOrderType())) {
			order.setOrderType("1");
		}
		if(StringUtils.isNotBlank(searchParam)){
			try {
				searchParam = java.net.URLDecoder.decode(searchParam,"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		order.setMerchant(super.merchant);
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			order.setCreateBy(user);
		}
		Page<Order> page = orderService.find(new Page<Order>(request, response), order, createStartDate, createEndDate, searchParam, timeSlot, 0); 
        return page;
	}

	@RequiresPermissions("ivm:order:view")
	@RequestMapping(value = "form")
	public String form(Order order, Model model) {
		model.addAttribute("order", order);
		return "modules/ivm/order/orderForm";
	}

	@RequiresPermissions("ivm:order:edit")
	@RequestMapping(value = "save")
	public String save(Order order, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, order)){
			return form(order, model);
		}
		orderService.save(order);
		addMessage(redirectAttributes, "保存商品订单'" + order.getOrderNo() + "'成功");
		return "redirect:"+Global.getAdminPath()+"/ivm/order/?repage";
	}
	
	@RequiresPermissions("ivm:order:edit")
	@RequestMapping(value = "delete")
	public String delete(String id, RedirectAttributes redirectAttributes) {
		orderService.delete(id);
		addMessage(redirectAttributes, "删除商品订单成功");
		return "redirect:"+Global.getAdminPath()+"/ivm/order/?repage";
	}
	
	/**
	 * 订单详情
	 * @param order
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("ivm:order:view")
	@RequestMapping(value = "orderDetail")
	public String orderDetail(String id, 
			@RequestParam(value="type", required=false, defaultValue="-1") int type,//标识是否是一键还原
			HttpServletRequest request, HttpServletResponse response, Model model) {
		Order order = orderService.get(id);
		boolean gift = false;//商品是否为新用户礼包
		for(OrderDetail oDetail:order.getDetailList()){
			if(oDetail.getProduct().getGift().equals("1")){
				gift = true;
				break;
			}
		}
        //Page<OrderDetail> page = orderService.findOrderDetails(new Page<OrderDetail>(request, response), order); 
        //List<OrderDetail> details = orderService.findOrderDetailList(order);
        //初次打开订单详情，将订单信息同步到送货单信息中,同时备份订单商品列表
        //如果是一键还原，也进行初始化，但不做保存
        if(order.getDeliveryInfo() == null || type == 1){
        	DeliveryInfo deliveryInfo = new DeliveryInfo();
        	//主键ID
        	String deliveryInfoId = IdGen.uuid();
        	deliveryInfo.setId(deliveryInfoId);
        	if(type==1){
        		deliveryInfo = order.getDeliveryInfo();
        		deliveryInfoId = deliveryInfo.getId();
        	}
        	//温馨提示
        	Prompt prompt = promptService.findByMerchantId(order.getMerchant().getId());
        	deliveryInfo.setPrompt(prompt.getPrompt());
        	deliveryInfo.setOrder(order);
        	//收货人信息
        	deliveryInfo.setName(order.getUserAddress().getName());
        	deliveryInfo.setPhone(order.getUserAddress().getPhone());
        	deliveryInfo.setAddress(order.getUserAddress().getDetailAddress());
        	if(order.getTimeSlot()!=null){
				deliveryInfo.setStartTime(order.getTimeSlot().getStartTime());
				deliveryInfo.setEndTime(order.getTimeSlot().getEndTime());
				if(StringUtils.isNotBlank(order.getTimeText())){
					deliveryInfo.setTimeText(order.getTimeText());
				}else{
					deliveryInfo.setTimeText(order.getTimeSlot().getTimeText());
				}
			}
        	deliveryInfo.setAmount(order.getAmount());
        	deliveryInfo.setRefund(0);
			deliveryInfo.setDeliveryNo(createUniqeAuthCode(order.getOrderNo()));//生成送货单号
			//封装派送单清单deliveryDetail
			List<DeliveryDetail> deliveryDetails = getOrderList(order);
			//封装订单备份清单orderDetailItem
			List<OrderDetailItem> orderDetailItems = getOrderItemList(order);
			if(type==-1){
				deliveryInfoService.save(deliveryInfo);
				deliveryDetailService.save(deliveryDetails);
				orderDetailItemService.save(orderDetailItems);
			}else{
				deliveryInfo.setTimeText(order.getTimeText());
				deliveryDetails = getDeliveryItemList(order);
				model.addAttribute("message", "一键还原送货单成功，保存后生效");
			}
			deliveryInfo = deliveryInfoService.get(deliveryInfoId);
			order.setDeliveryList(deliveryDetails);
			order.setDeliveryInfo(deliveryInfo);
        }
        //获取派送费信息
        DeliveryFee deliveryFee = deliveryFeeService.findByMerchantId(merchant.getId());
        if(StringUtils.isBlank(deliveryFee.getOpenState()) || deliveryFee.getOpenState().equals("0")){
        	model.addAttribute("fee", 0);
        	model.addAttribute("lowFee", 0);
        }else{
        	if(order.getCreateDate().getTime()>=deliveryFee.getBeginDate().getTime() && order.getCreateDate().getTime()<=deliveryFee.getEndDate().getTime()){
        		model.addAttribute("fee", deliveryFee.getAmount());
        		model.addAttribute("lowFee", deliveryFee.getLowFee());
        	}else{
        		model.addAttribute("fee", 0);
            	model.addAttribute("lowFee", 0);
        	}
        }
        model.addAttribute("order", order); //订单信息
		model.addAttribute("deliveryInfo", order.getDeliveryInfo()); //送货信息
		List<DeliveryDetail> deliveryList = order.getDeliveryList();
		model.addAttribute("orderList", deliveryList); //订单商品信息
//		model.addAttribute("userAddress", order.getUserAddress()); //用户地址信息
		model.addAttribute("toCreate", false);
		model.addAttribute("gift", gift);
		return "modules/ivm/order/orderDetail";
	}
	//送货单号
	public String createUniqeAuthCode(String orderNo) {
		String authCode = "D"+orderNo.substring(2);
		return authCode;
	}
	
	//封装订单商品详情list
	private List<DeliveryDetail> getOrderList(Order order) {
		//订单商品list
		List<DeliveryDetail> details = new ArrayList<DeliveryDetail>();
		int i=0;
		for (OrderDetail detail : order.getDetailList()) {
			DeliveryDetail deliveryDetail = new DeliveryDetail();
			deliveryDetail.setSort(i);
			deliveryDetail.setId(IdGen.uuid());
			deliveryDetail.setType(detail.getType());
			deliveryDetail.setMerchant(detail.getMerchant());
			deliveryDetail.setOrder(detail.getOrder());
			deliveryDetail.setProduct(detail.getProduct());
			deliveryDetail.setUser(detail.getUser());
			deliveryDetail.setNumber(detail.getNumber());
			deliveryDetail.setPrice(detail.getPrice());
			deliveryDetail.setAmount(detail.getAmount());
			details.add(deliveryDetail);
			i++;
		}
		return details;
	}
	
	//封装订单商品备份详情list
	private List<OrderDetailItem> getOrderItemList(Order order) {
		//订单商品list
		List<OrderDetailItem> details = new ArrayList<OrderDetailItem>();
		int i=0;
		for (OrderDetail detail : order.getDetailList()) {
			OrderDetailItem orderDetailItem = new OrderDetailItem();
			orderDetailItem.setSort(i);
			orderDetailItem.setId(IdGen.uuid());
			orderDetailItem.setType(detail.getType());
			orderDetailItem.setMerchant(detail.getMerchant());
			orderDetailItem.setOrder(detail.getOrder());
			orderDetailItem.setProduct(detail.getProduct());
			orderDetailItem.setUser(detail.getUser());
			orderDetailItem.setNumber(detail.getNumber());
			orderDetailItem.setPrice(detail.getPrice());
			orderDetailItem.setAmount(detail.getAmount());
			details.add(orderDetailItem);
			i++;
		}
		return details;
	}
	
	//封装订单商品备份详情list(一键还原时用)
	private List<DeliveryDetail> getDeliveryItemList(Order order) {
		//订单商品list
		List<DeliveryDetail> details = new ArrayList<DeliveryDetail>();
		int i=0;
		for (OrderDetailItem detail : order.getDetailItemList()) {
			DeliveryDetail detailItem = new DeliveryDetail();
			detailItem.setSort(i);
			detailItem.setId(IdGen.uuid());
			detailItem.setType(detail.getType());
			detailItem.setMerchant(detail.getMerchant());
			detailItem.setOrder(detail.getOrder());
			detailItem.setProduct(detail.getProduct());
			detailItem.setUser(detail.getUser());
			detailItem.setNumber(detail.getNumber());
			detailItem.setPrice(detail.getPrice());
			detailItem.setAmount(detail.getAmount());
			details.add(detailItem);
			i++;
		}
		return details;
	}
	
	/**
	 * 保存订单详情
	 * @param order
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "saveDetail")
	public String saveOrderDetail(String[] sorts,String[] detailIds, String[] products, Integer[] numbers, Double[] prices, Double[] amounts, DeliveryInfo deliveryInfo, Model model, RedirectAttributes redirectAttributes) {
		int len = 0;
		if(numbers != null){
			len = numbers.length;
		}
		String confirm = deliveryInfo.getOrder().getConfirm();
		deliveryInfoService.save(deliveryInfo);
		List<DeliveryDetail> deliveryDetails = new ArrayList<DeliveryDetail>();
    	Order order = orderService.get(deliveryInfo.getOrder().getId());
    	//删除送货单商品详情List
    	for(DeliveryDetail deliveryDetail : order.getDeliveryList()){
    		deliveryDetailService.delete(deliveryDetail.getId());
    	}
    	boolean gift = false;//商品是否为新用户礼包
    	//重新封装送货单商品详情List
    	for (int i = 0; i < len; i++) {
    		DeliveryDetail details = new DeliveryDetail();
    		details.setId(IdGen.uuid());
			details.setMerchant(order.getMerchant());
			details.setOrder(deliveryInfo.getOrder());
			Product product = productService.get(products[i]);
			if(product.getGift().equals("1")){
				gift = true;
			}
			details.setProduct(product);
			details.setUser(order.getUser());
			details.setNumber(numbers[i]);
			details.setPrice(prices[i]);
    		details.setAmount(amounts[i]);
    		details.setSort(Integer.valueOf(sorts[i]));
    		deliveryDetails.add(details);
    	}
    	List<OrderDetail> orderDetails = new ArrayList<OrderDetail>();
    	//删除订单商品详情List
    	for(OrderDetail orderDetail : order.getDetailList()){
    		orderDetail.setDelFlag("1");
    		orderDetails.add(orderDetail);
    	}
    	//重新封装订单商品详情List
    	for (int i = 0; i < len; i++) {
    		OrderDetail detail = new OrderDetail();
    		detail.setId(IdGen.uuid());
    		detail.setMerchant(order.getMerchant());
    		detail.setOrder(order);
			Product product = productService.get(products[i]);
			detail.setProduct(product);
			detail.setUser(order.getUser());
			detail.setNumber(numbers[i]);
			detail.setPrice(prices[i]);
			detail.setAmount(amounts[i]);
			detail.setSort(i);
			orderDetails.add(detail);
    	}
    	order.setConfirm(confirm);//保存订单：状态
    	order.setDetailList(orderDetails);
    	order.setRemarks(deliveryInfo.getRemarks());
    	orderService.save(order);
    	//获取派送费信息
		DeliveryFee deliveryFee = deliveryFeeService.findByMerchantId(merchant.getId());
		if(StringUtils.isBlank(deliveryFee.getOpenState()) || deliveryFee.getOpenState().equals("0")){
			model.addAttribute("fee", 0);
			model.addAttribute("lowFee", 0);
		}else{
			if(order.getCreateDate().getTime()>=deliveryFee.getBeginDate().getTime() && order.getCreateDate().getTime()<=deliveryFee.getEndDate().getTime()){
        		model.addAttribute("fee", deliveryFee.getAmount());
        		model.addAttribute("lowFee", deliveryFee.getLowFee());
        	}else{
        		model.addAttribute("fee", 0);
            	model.addAttribute("lowFee", 0);
        	}
		}
    	deliveryDetailService.save(deliveryDetails); //保存送货单详情
    	model.addAttribute("order", order); //订单信息
		model.addAttribute("deliveryInfo", order.getDeliveryInfo()); //送货信息
		model.addAttribute("orderList", deliveryDetails); //订单商品信息
		model.addAttribute("toCreate", true);
		model.addAttribute("gift", gift);
		model.addAttribute("message", "保存成功");
		return "modules/ivm/order/orderDetail";
	}
	
	//点击完成订单时，打开订单信息面板
	@RequestMapping(value = "showFinishOrderPanl")
	public String showFinishOrderPanl(
			String id,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		Order order = orderService.get(id);
		model.addAttribute("order", order);
		DeliveryInfo deliveryInfo = order.getDeliveryInfo();
		model.addAttribute("deliveryInfo", deliveryInfo);
		return "modules/ivm/order/finishOrderPanl";
	}
	//提交订单完成
	@RequestMapping(value = "finishOrder")
	public String finishOrder(String id, String receiptMarks, Date signTime, String type, 
			double realAmount, Model model) {
		//解码
		if(StringUtils.isNotBlank(receiptMarks)){
			try {
				receiptMarks = java.net.URLDecoder.decode(receiptMarks,"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		String[] orders = id.split(",");
		for (String orderId : orders) {
			orderService.finishOrder(orderId);
			Order order = orderService.get(orderId);
			{
				DeliveryInfo deliveryInfo = order.getDeliveryInfo();
				deliveryInfo.setReceiptMarks(receiptMarks);
				if(signTime==null){
					signTime = new Date();
				}
				deliveryInfo.setSignTime(DateUtils.parseDate(DateUtils.formatDateTime(signTime, DateUtils.parsePatterns[2])));
				if(order.getPayType().equals("1")){
					deliveryInfo.setRealAmount(realAmount);
				}else{
					deliveryInfo.setRealRefund(realAmount);
				}
				deliveryInfoService.save(deliveryInfo);
				if(type.equals("1")){
					order.setFinish("0");
					orderService.save(order);
					model.addAttribute("message", "复核提交成功，等待结账");
					model.addAttribute("type", "success");
					return "modules/ivm/order/finishOrderPanl";
				}
				DeliveryIndent deliveryIndent = order.getDeliveryIndent();
				deliveryIndent.setDeliveryDate(DateUtils.parseDate(DateUtils.formatDateTime(new Date(), DateUtils.parsePatterns[2])));
				indentService.save(deliveryIndent);
				//向流程明细表插入记录
				WorkFlowDetail workFlowDetail = new WorkFlowDetail();
				workFlowDetail.setFlowNode("2");
				workFlowDetail.setWorkFlow(order.getWorkFlow());
				workFlowDetail.setDeliveryIndent(order.getDeliveryIndent());
				workFlowDetail.setRemarks("完成订单派送.");
				workFlowDetailService.save(workFlowDetail);
				int flag = orderService.updateOrderTypeById(orderId,"2"); //更新订单状态和付款状态
			}
			//全部处理完成后，做出库
			{
				List<ProductOutDetail> outDetails = Lists.newArrayList();
				List<Product> products = Lists.newArrayList();
				for (DeliveryDetail deliveryDetail : order.getDeliveryList()) {
					//构建商品信息
					Product product = deliveryDetail.getProduct();
					List<ProductInventoryDetail> inventoryDetailList = product.getInventoryDetailList();
					//构建出库记录信息
					ProductOutDetail outDetail = new ProductOutDetail();
					outDetail.setMerchant(product.getMerchant());
					outDetail.setProduct(product);
					outDetail.setNumber(deliveryDetail.getNumber());
					outDetail.setWeight(deliveryDetail.getNumber()*product.getSpecNum());
					if (inventoryDetailList.size()>0) {
						ProductInventoryDetail inventoryDetail = inventoryDetailList.get(inventoryDetailList.size()-1);
						outDetail.setAmount(FloatFormat.m2_2(outDetail.getWeight()*inventoryDetail.getAmount()/inventoryDetail.getWeight()));
					}else {
						if(product.getStock()<=0){
							outDetail.setAmount(FloatFormat.m2_2(deliveryDetail.getAmount()));
						}else{
							outDetail.setAmount(FloatFormat.m2_2(outDetail.getWeight()*product.getStockAmount()/product.getStock()));
						}
					}
					outDetails.add(outDetail);
					
					//出库，商品库存变更
					product.setStock(product.getStock()-(deliveryDetail.getNumber()*product.getSpecNum()));
					product.setStockAmount(FloatFormat.m2_2(product.getStockAmount()-outDetail.getAmount()));
					products.add(product);
				}
				//开始出库
				productOutDetailService.save(outDetails);
				productService.save(products);
			}
			model.addAttribute("order", order);
		}
		model.addAttribute("message", "订单完成处理成功，等待结账");
		model.addAttribute("type", "success");
		return "modules/ivm/order/finishOrderPanl";
	}
	//打开财务结款面板
	@RequestMapping(value = "showFinishPayPanl")
	public String showFinishPayPanl(
			String id,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		Order order = orderService.get(id);
		DeliveryInfo deliveryInfo = order.getDeliveryInfo();
		model.addAttribute("order", order);
		model.addAttribute("deliveryInfo", deliveryInfo);
		return "modules/ivm/order/finishPayPanl";
	}
	//确认财务结款
	@RequestMapping(value = "finishPayOrder")
	public String finishPayOrder(String id, String type, String payCode, Model model) {
		Order order = orderService.get(id);
		if(super.merchant.getPayCode().equals(payCode)){
			order.setFinish(type);
			orderService.save(order);
			model.addAttribute("message", "提交成功");
			model.addAttribute("type", "success");
		}else{
			model.addAttribute("message", "密码不正确，请检查修改");
			model.addAttribute("type", "");
		}
		DeliveryInfo deliveryInfo = order.getDeliveryInfo();
		model.addAttribute("order", order);
		model.addAttribute("deliveryInfo", deliveryInfo);
		return "modules/ivm/order/finishPayPanl";
	}
	
	@RequiresPermissions("ivm:order:edit")
	@RequestMapping(value = "cancelOrder")
	public String cancelOrder(String id, RedirectAttributes redirectAttributes) {
		orderService.delete(id);
		addMessage(redirectAttributes, "订单取消处理成功");
		return "redirect:"+Global.getAdminPath()+"/ivm/order/?repage";
	}
	
	/**
	 * 打开支付状态面板
	 */
	@RequestMapping(value = "showPayType")
	public String showPayType(
			String id,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		Order order = orderService.get(id);
		model.addAttribute("order", order);
		return "modules/ivm/order/editPayType";
	}
	
	/**
	 * 修改支付方式，更新支付状态
	 */
	@RequestMapping(value = "changeOpenType")
	public String changeOpenType(
			Order order,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		orderService.save(order);
		model.addAttribute("order", order);
		model.addAttribute("type", "success");
		return "modules/ivm/order/editPayType";
	}
	
	/**
	 * 打开取消订单面板
	 */
	@RequestMapping(value = "showCancelPanl")
	public String showCancelPanl(
			String id,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		Order order = orderService.get(id);
		model.addAttribute("order", order);
		return "modules/ivm/order/cancelPanl";
	}
	
	/**
	 * 确认取消订单，更新订单状态
	 */
	@RequestMapping(value = "confirmCancelOrder")
	public String confirmCancelOrder(
			Order order,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		order.setDelFlag("1");
		orderService.save(order);
		model.addAttribute("order", order);
		model.addAttribute("type", "success");
		return "modules/ivm/order/cancelPanl";
	}
	
	/**
	 * 导出订单excel
	 * @param purchase
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("ivm:order:view")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public @ResponseBody Object exportFile(String[] orderIds, String[] timeSlot,
    		@RequestParam(value="orderType", required=false, defaultValue="") String orderType,
    		@RequestParam(value="createStartDate", required=false, defaultValue="") String createStartDate, 
			@RequestParam(value="createEndDate", required=false, defaultValue="") String createEndDate, 
			@RequestParam(value="searchParam", required=false, defaultValue="") String searchParam,
			//@RequestParam(value="slotId", required=false, defaultValue="") String slotId,
			@RequestParam(value="memberId", required=false, defaultValue="") String memberId,
    		HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		String filePath = null;
		if(StringUtils.isNotBlank(searchParam)){
			try {
				searchParam = java.net.URLDecoder.decode(searchParam,"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		try {
			List<Order> orderList = Lists.newArrayList();
			if(orderIds == null){//全部导出
				Order order = new Order();
				order.setOrderType(orderType);
				//order.setTimeSlot(new TimeSlot(slotId));
				order.setMerchant(new Merchant(super.merchant.getId()));
				Page<Order> page = orderService.find(new Page<Order>(request, response), order, createStartDate, createEndDate, searchParam, timeSlot, 1); 
				orderList = page.getList();
			}else{
				orderList = orderService.findSelects(orderIds);
			}
			//购买商品总数：用户excel标题行的排版
			int maxChildList = 0;
			for(Order order: orderList){
				int childLen = 0;
				if(order.getDeliveryList() != null && order.getDeliveryList().size()>0){
					childLen = order.getDeliveryList().size();
				}else{
					childLen = order.getDetailList().size();
				}
				if(childLen > maxChildList){
					maxChildList = childLen;
				}
			}
		    //获取文件保存路径
		    filePath=Global.getConfig("upload.path");
		    String childDir = "template/";
		    filePath += (childDir +"Order_List.xls");
			File excelFile = new File(filePath);
			excelFile.createNewFile();
			//构建数据
			//生成excel数据列的标题
			String columnValue = "订单编号,下单时间,下单人,下单人手机,收货人,收货人手机,收货地址,送货时间,要求收货时间,实际送达时间,支付方式";
			for(int i=1;i<maxChildList+1;i++){
				columnValue += ",品名"+i+",金额"+i;
			}
			columnValue += ",订单金额";
			String[] columnValues = columnValue.split(",");
			List<String> columns = new ArrayList<String>();
			for (int i=0; i<columnValues.length; i++) {
					columns.add(columnValues[i]);
			}
			//生成excel单元格数据
			//生成excel单元格数据-第1行的数据
			Map<String, List<String>> data = new LinkedHashMap<String, List<String>>();
			List<String> rowData = new ArrayList<String>();
			for(Order order: orderList){
				rowData = new ArrayList<String>();
				rowData.add(order.getOrderNo());
				rowData.add(DateUtils.formatDateTime(order.getCreateDate()));
				rowData.add(order.getUser().getName());
				rowData.add(order.getUser().getMobile());
				if(order.getDeliveryInfo() != null){
					rowData.add(order.getDeliveryInfo().getName());
					rowData.add(order.getDeliveryInfo().getPhone());
					rowData.add(order.getDeliveryInfo().getAddress());
				}else{
					rowData.add(order.getUser().getName());
					rowData.add(order.getUser().getMobile());
					rowData.add(order.getUserAddress().getDetailAddress());
				}
				
				Date createTime = order.getCreateDate();//下单时间
				Date signDate = createTime;
				String signTime = ""; //收货时间
				if(order.getDeliveryInfo() != null){
					signTime = order.getDeliveryInfo().getTimeText();
				}else{
					if(order.getTimeSlot()!=null){
						signTime = order.getTimeSlot().getTimeText();
					}
				}
				//初始化送货日期
				String deliveryTime = "";
				if(signTime != null && signTime.indexOf("次日")>-1){
					signDate = DateUtils.GetLastDate(createTime, 1);
					rowData.add(DateUtils.formatDateTime(signDate,"yyyy-MM-dd")+signTime.substring(2));
					deliveryTime = signTime.substring(2).trim();
				}else if(signTime != null && signTime.indexOf("后日")>-1){
					signDate = DateUtils.GetLastDate(createTime, 2);
					rowData.add(DateUtils.formatDateTime(signDate,"yyyy-MM-dd")+signTime.substring(2));
					deliveryTime = signTime.substring(2).trim();
				}else{
					rowData.add(DateUtils.formatDateTime(signDate,"yyyy-MM-dd"));
				}
				//将送货时间保存到deliveryInfo的deliveryDate中
				//DeliveryInfo info = deliveryInfoService.get(order.getDeliveryInfo().getId());
				//info.setDeliveryDate(signDate);
				//info.setDeliveryNo(createUniqeAuthCode(order.getOrderNo()));
				//info.setDeliveryTime(deliveryTime);
				//deliveryInfoService.save(info);
				//System.out.println("初始化送货日期："+info.getId()+"------------------"+signDate);
				rowData.add(signTime);
				if(order.getDeliveryIndent() != null && order.getDeliveryIndent().getDeliveryDate() != null){
					rowData.add(DateUtils.formatDateTime(order.getDeliveryIndent().getDeliveryDate()));
				}else{
					rowData.add("");
				}
				String payType="货到付款";
				if(order.getPayType().equals("2")){
					payType="支付宝";
				}else if(order.getPayType().equals("3")){
					payType="银联";
				}else if(order.getPayType().equals("4")){
					payType="微信";
				}
				rowData.add(payType);
				int nums = 0;
				if(order.getDeliveryList() != null && order.getDeliveryList().size()>0){
					for(DeliveryDetail deliveryDetail:order.getDeliveryList()){
						rowData.add(deliveryDetail.getProduct().getName());
						rowData.add(deliveryDetail.getAmount()+"");
						nums++;
					}
				}else{
					for(OrderDetail orderDetail:order.getDetailList()){
						rowData.add(orderDetail.getProduct().getName());
						rowData.add(orderDetail.getAmount()+"");
						nums++;
					}
				}
				for(int i=0;i<maxChildList-nums;i++){
					rowData.add("");
					rowData.add("");
				}
				rowData.add(order.getAmount()+"");
				data.put(order.getId()+"", rowData);
			}
			//调用ExcelManager对象write数据
			excelManager.writeExcel(excelFile, "订单", columns, data);
			//返回文件名
			//response.getWriter().print(fileURL);
		} catch (Exception e) {
			e.printStackTrace();
			return getStatusBean(400, "订单导出失败");
		}
		//return "redirect:"+Global.getAdminPath()+"/ivm/order/?repage";
		return getStatusBean(200, filePath);
    }
	//导出派送单word
	@RequiresPermissions("ivm:order:view")
    @RequestMapping(value = "exportWord", method=RequestMethod.POST)
    public @ResponseBody Object exportWord(String[] orderIds, 
    		@RequestParam(value="orderType", required=false, defaultValue="") String orderType,
    		@RequestParam(value="createStartDate", required=false, defaultValue="") String createStartDate, 
			@RequestParam(value="createEndDate", required=false, defaultValue="") String createEndDate, 
			@RequestParam(value="searchParam", required=false, defaultValue="") String searchParam,
			//@RequestParam(value="slotId", required=false, defaultValue="") String slotId,
			@RequestParam(value="timeSlot", required=false, defaultValue="") String[] timeSlot,
			@RequestParam(value="memberId", required=false, defaultValue="") String memberId,
    		HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		if(StringUtils.isNotBlank(searchParam)){
			try {
				searchParam = java.net.URLDecoder.decode(searchParam,"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		String uploadPath=Global.getConfig("upload.path");//生成的文件存放路径
		String childDir = "template/";
		uploadPath += childDir;
		File saveDirFile = new File(uploadPath);
		if (!saveDirFile.exists()) {
			saveDirFile.mkdirs();
		}
		List<Order> orders = Lists.newArrayList();
		if(orderIds == null){//全部导出
			Order order = new Order();
			order.setOrderType(orderType);
			//order.setTimeSlot(new TimeSlot(slotId));
			order.setMerchant(new Merchant(super.merchant.getId()));
			Page<Order> page = orderService.find(new Page<Order>(request, response), order, createStartDate, createEndDate, searchParam, timeSlot, 1); 
			orders = page.getList();
		}else{
			orders = orderService.findSelects(orderIds);
		}
		//温馨提示
    	Prompt prompt = promptService.findByMerchantId(super.merchant.getId());
		//把温馨提示绑定到送货单中
		for(Order order:orders){
			if(order.getDeliveryInfo()==null){
				order.setPrompt(prompt.getPrompt());
			}else{
				if(order.getDeliveryInfo().getPrompt()==null){
					order.setPrompt("");
				}else{
					order.setPrompt(order.getDeliveryInfo().getPrompt());
				}
			}
		}
	    //生成word
	    ExportDeliveryUtil dh=new ExportDeliveryUtil();
	    if(orders.size() == 1){//如果是导出单个派送单,直接返回文件路径
	    	String wordNname = orders.get(0).getDeliveryNo()+orders.get(0).getName();
	    	uploadPath += wordNname;
	    	dh.createDoc(orders,uploadPath);
	    	return getStatusBean(200, childDir+wordNname+".doc");
	    }
	    String zipName = orders.get(0).getMerchant().getId();
	    uploadPath += zipName;
	    dh.createDocs(orders,uploadPath);
	    //return getStatusBean(200, fileUrl+".doc");
	    
	    //压缩word文件夹
	    FileZip book = new FileZip();
	    String fileZip=uploadPath+".zip";//压缩后的文件路径
	    try {
			book.createZip(uploadPath+".doc",fileZip);//要压缩的文件夹
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    return getStatusBean(200, childDir+zipName+".zip");
	}
}
